package com.csdj.springboottest.util;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.Map;

/**
 * 发送http请求  jdk 11以上使用
 */
public class HttpUtil {

    private static Logger log = LoggerFactory.getLogger("httputil");


    /**
     * 实际发送请求
     * @param url  请求地址
     * @param method 请求方法
     * @param headers 请求头信息
     * @param data    请求数据
     * @return
     */
    private static String doRequest(String url, String method,Map<String,String> headers,String data){
        HttpClient client = HttpClient.newHttpClient();
        final HttpRequest.Builder builder = HttpRequest.newBuilder(URI.create(url));
        if(headers != null){
            headers.entrySet().stream().forEach(entry -> builder.header(entry.getKey(),entry.getValue()));
        }
        switch(method){
            case "get": ;
            case "GET":
                builder.method("get",HttpRequest.BodyPublishers.noBody());
                break;
            case "put":;
            case "PUT":
                builder.method("put",HttpRequest.BodyPublishers.ofString(data));
                break;
        }
        builder.timeout(Duration.ofSeconds(30));
        final HttpRequest request = builder.build();
        try {
            final HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            if(response.statusCode() == 200){
                return response.body();
            }else{
                log.error("发送http请求失败 errcode:{} url:{}",response.statusCode(),url);
                return null;
            }

        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String get(String url){
        return doRequest(url,"get",null,null);
    }

    public static void main(String[] args) {
        System.out.println(get("https://www.baidu.com"));
    }
}
